package com.xiashitech.agent.instrumentation.biz.userinfo.springsecurity;

import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.base.AbstractAttributesExtractor;
import com.xiashitech.agent.instrumentation.base.context.TraceContextVars;
import com.xiashitech.agent.instrumentation.bridge.Java8Bridge;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.interfaces.agent.dto.SystemInfoDTO;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import org.jetbrains.annotations.Nullable;

import java.util.Optional;

public class XSAuthenticationAttributesExtractor extends AbstractAttributesExtractor<AuthenticationData, Void> {

    @Override
    public void onXSStart(AttributesBuilder attributesBuilder, Context context, AuthenticationData authenticationData) {
        try{

        }catch (Throwable e){
            StartConfig.throwableStackPrinter(e);
        }
    }


    @Override
    public void onXSEnd(AttributesBuilder attributesBuilder, Context context, AuthenticationData authenticationData, @Nullable Void unused, @Nullable Throwable throwable) {
        try {
            if (authenticationData == null) return;
            //Baggage baggage = BaggageUtil.mergeBaggageFromContext(Java8Bridge.currentForBaggage(),context).build();
            Object principalObj = authenticationData.getPrincipal();
            if (principalObj == null) return;
            Optional<UserRequest> optional = Java8Bridge.executeRuleForUserInfoMatchRule(authenticationData);
            String userId = null;
            if(optional.isPresent()) {
                UserRequest userRequest = optional.get();
                userId = userRequest.getUserid();
                authenticationData.setUserId(userId);
                setAttributes(attributesBuilder,userRequest,context,false);
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
    }

    private void setAttributes(AttributesBuilder attributes,UserRequest userRequest,Context context,Boolean sessionUpdate) {
        try {
            attributes.put("xs.userId",userRequest.getUserid() == null ? "" : userRequest.getUserid());
            attributes.put("xs.sessionId",userRequest.getSessionId() == null ? "" : userRequest.getSessionId());
            attributes.put("xs.requestDate",userRequest.getRequestDate() == null ? "" : userRequest.getRequestDate().toString());
            attributes.put("xs.sessionUpdate",sessionUpdate);
            attributes.put("xs.systemId", StartConfig.getParamValueFromKey(StartConfig.systemId));
            attributes.put("xs.systemReg", SystemInfoDTO.getConfig().getSystemExist());
            attributes.put("xs.sourceSystemId", BaggageUtil.getTraceVar(context, "xsAuthSystemId") == null ? StartConfig.getParamValueFromKey(StartConfig.systemId):BaggageUtil.getTraceVar(context, "xsAuthSystemId"));
            TraceContextVars.get()
                    .set("xs.userId",userRequest.getUserid() == null ? "" : userRequest.getUserid())
                    .set("xs.sessionId",userRequest.getSessionId() == null ? "" : userRequest.getSessionId())
                    .set("xs.requestDate",userRequest.getRequestDate() == null ? "" : userRequest.getRequestDate().toString())
                    .set("xs.sessionUpdate",sessionUpdate.toString());
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
    }

    @Override
    public String getAttributesExtractorName() {
        return XSAuthenticationAttributesExtractor.class.getName();
    }
}
